<?php


namespace app\index\controller;


use app\service\CommissionService;
use app\service\DepositService;
use app\service\IGeTuiService;
use base\Excel;
use Redis\Redis;
use think\Controller;
use think\Db;

class Demo extends Controller
{
    function serviceNum()
    {
        $bizId = 1;
        # 全部
        $all = Db::table('orders o')->where("o.biz_id = " . $bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1")->count();
        # 服务中
        $serving = Db::table('orders o')
            ->join('order_server os', 'os.order_number = o.order_number', 'left')
            ->join('order_biz ob', 'ob.order_number = o.order_number', 'left')
            ->where("o.biz_id = " . $bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1")
            ->where("os.status = 2 or ob.status = 4")
            ->count('o.id');
        # 等待中
        $waiting = Db::table('orders o')
            ->join('order_server os', 'os.order_number = o.order_number', 'left')
            ->join('order_biz ob', 'ob.order_number = o.order_number', 'left')
            ->where("o.biz_id = " . $bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1")
            ->where("(os.status=1 or os.status=5) or ob.status = 1 or ((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))=0")
            ->count('o.id');
        # 已完成
        $finishIng = Db::table('orders o')
            ->join('order_server os', 'os.order_number = o.order_number', 'left')
            ->join('order_biz ob', 'ob.order_number = o.order_number', 'left')
            ->where("o.biz_id = " . $bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1")
            ->where("(select count(os.id) from order_server os where os.order_number=o.order_number and os.status in (1,2)) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status in (1,4)))=0
                                             and (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))>0")
            ->count('o.id');
        dump($all);
        dump($serving);
        dump($waiting);
        dump($finishIng);
        $static = Db::query("select count(o.id) all_num,
                                        (select count(o.id) from orders o where o.biz_id = " . $bizId . " 
                                        and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1  and (
                                            (select count(os.id) from order_server os where os.order_number=o.order_number and os.status=2)>0
                                             or (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status =4)>0
                                             )) servicing,
                                         (select count(o.id) from orders o where o.biz_id = " . $bizId . " 
                                         and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6  and hidden_status = 1 
                                         and (
                                            (
                                            (select count(os.id) from order_server os where os.order_number=o.order_number and (os.status=1 or os.status=5))>0)
                                             or ((select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status =1)>0)
                                             or (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))=0)
                                             ))
                                                waiting,
                                             (select count(o.id) from orders o where o.biz_id =" . $bizId . " and (o.order_type=2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1 
                                             and (
                                             (select count(os.id) from order_server os where os.order_number=o.order_number and os.status in (1,2)) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number and ob.status in (1,4)))=0
                                             and (((select count(os.id) from order_server os where os.order_number=o.order_number) + 
                                             (select count(ob.id) from order_biz ob where ob.order_number=o.order_number))>0)
                                             ) finishIng,
                                        (select count(o.id) from orders o where o.id not in (select o.id from orders o,order_server os where o.biz_id = " . $bizId . " 
                                        and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1  and (os.status!=3 and os.status!=4) and os.order_number=o.order_number group by o.id)
                                        and o.biz_id = " . $bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6) notFinish
                                        from orders o
                                      where o.biz_id = " . $bizId . " and (o.order_type = 2 or o.order_type = 3) and o.order_status = 6 and hidden_status = 1 ");
        dump($static);
    }

    function sqlDemo(){
        $channel = Db::table("channel")->where(array("member_id"=>1733,"channel"=>10))->where("pid > 0")
            ->order("id desc")->find();
        dump($channel);
    }

    function demo()
    {
//        $a = Db::table('orders')->field('pay_type')->where(array('order_number' => '202107021455203043000001'))->value('pay_type');
//        dump($a);
//        die;
        $bizId = input('get.biz_id') ?? 408;
        $redis = new Redis();
        $payRedisInfo = $redis->hGet('payRedis' . $bizId);
        dump($payRedisInfo);
//        $redis->delete('settlementTask' . $bizId);
        $status = $redis->get('settlementTask' . $bizId);
        dump($status);
        $info = Db::table('biz_settlement bs')
            ->field('bs.id,bs.price,bs.biz_id,commission_price,tobe_settled,bs.order_number')
            ->join('orders o', 'o.order_number = bs.order_number', 'left')
            ->where(array('bs.settlement_status' => '1', 'bs.desposit_status' => '1', 'o.evaluation_status' => '1', 'bs.type' => '1', 'bs.mark' => '1'))
            ->where("o.order_over <= '" . date('Y-m-d H:i:s', strtotime('-1 day')) . "'")
            ->order('bs.id asc')
            ->select();
        dump($info);
        die;
        $stationlist = $redis->hGet("stationlist" . $bizId);
        dump($stationlist);
        $station_id = input('get.station_id');
        $stationEmployee = $redis->hGetJson('stationEmployee', strval($station_id));
        dump($stationEmployee);
    }

    function muban()
    {
        $memberId = input('get.member_id');
        $_openid = Db::table('member')
            ->field('member_openid')
            ->where(array('id' => $memberId))
            ->find();
        # 服务评价
        $config = config('templateMsg.comment');
        $data = array(
            'first' => array('value' => $config['first'], 'color' => '#000000'),
            'keyword1' => array('value' => '测试门店', 'color' => '#000000'),//门店名称
            'keyword2' => array('value' => date('Y-m-d H:i:s'), 'color' => '#000000'), //消费时间
            'remark' => array('value' => $config['remark'], 'color' => '#000000'),
        );
        $_res = ThirdParty::sendTemplate($_openid['member_openid'], '2FlURfQREBqmhE_K0CfhRUZXVyD-A-gtuNKD4QX1PTA', 'http://web.elianchefu.com/#/pages/mine/index', $data);
        dump($_res);
    }


    function aliRefund()
    {
        $refund = new OrdersPay();
        $order_number = input('get.o');
        $refund_amount = input('get.m');
        $res = $refund->aliRefund($order_number, $refund_amount);
        dump($res);
    }

    function wxRefund()
    {
        $order_number = input('get.o');
        $refund_amount = input('get.m');
        $order = [
            'out_trade_no' => $order_number,
            'total_fee' => $refund_amount * 100,
            'refund_fee' => $refund_amount * 100,
            'refund_desc' => '订单退款',
        ];
        $payment = new Payment($order);
        $res = $payment->refund_wx();
        dump($res);
    }

    function paySuccess()
    {
//        return;
        $p = new Payment();
        if (input('get.t') == 1) {
            $orderInfo = Db::table('orders')->field('order_number,pay_type,pay_price')
                ->where(array('order_number' => '202111141036243042200001'))
                ->select();
            dump($orderInfo);
            foreach ($orderInfo as $k => $v) {
                $res = $p->paySuccess($v['order_number'], $v['pay_type'], $v['pay_price'], true, false);
                dump($res);
            }
        } else {
            $res = $p->paySuccess(input('get.o'), input('get.p'), input('get.m'));
            dump($res);
        }
    }

    function status()
    {
        $p = new OrdersPay();
        $res = $p->OrderStatusQuery('202204090816153069300001', 1, 28, false);
        dump($res);
    }
    function orderStatus()
    {
        $p = new OrdersPay();
        $res = $p->OrderStatusQuery('202204090816153069300001', 1, 30, false);
        dump($res);
    }
    function payRedis()
    {
        $redis = new Redis();
//        $redis->hSetJson('payRedis','abc',array('pay_type'=>1,'time'=>date('Y-m-d H:i:s')));
//        $redis->hSetJson('payRedis','abcd',array('pay_type'=>2,'time'=>date('Y-m-d H:i:s')));
//        $redis->hSetJson('payRedis','abcde',array('pay_type'=>3,'time'=>date('Y-m-d H:i:s')));
//        $a = $redis->delete('payRedis');
//        dump($a);
        $res = $redis->hGet('payRedis' . input('get.biz_id'));
        dump($res);
    }

    function depositDemo()
    {
        DepositService::depositting();
        var_dump(123);
    }

    function bizSettlement()
    {
        $info = Db::query("select id,order_number,server_id,coupon_mark,
       if(custommark=1,(select service_title from service where id =os.server_id),
                (select custom_server_title from customserver where id=os.server_id)) serviceTitle,
       status,price,custommark,order_starttime,original_price,
(select biz_id from orders where order_number = os.order_number) biz_id,
(select car_liences from orders where order_number = os.order_number) car_num,
if(custommark=1,(select biz_pid from service where id =os.server_id),0) biz_pid,
(select score from evaluation_score where orderserver_id = os.id limit 1) score,       
if(custommark=1,(select relation_eva from service where id =os.server_id),2) relation_eva,price_settlement,final_settlement       
 from order_server os where (select count(id) from order_server ob where os.order_number = ob.order_number) > 1 
 and order_number != 'undefined' and (select biz_id from orders where order_number = os.order_number)  != 408 and final_settlement > 0
and date(order_starttime) >= '2021-10-13'
 order by order_number desc");

        $bizArr = array();
        $res = array();
        foreach ($info as $k => $v) {
            $settlement_medium = config('ecarcoo.comment_rate_settlement')['medium'];
            # 获取门店信息
            $bizInfo = getsBizInfoArray($v['biz_id'], 1);
            $orderInfo = Db::table('orders')->where(array('order_number' => $v['order_number']))->find();
            $payType = $orderInfo['pay_type'];
            $orderNumber = $v['order_number'];
            $settlement_service_info = 0;
            if ($v['custommark'] == 1) {
                # 判断是否使用了卡券支付(判断卡券的结算金额)
                $memberVoucherInfo = Db::table('member_voucher')->field('id,settlement_price,voucher_cost')
                    ->where("id = (select voucher_id from log_cashcoupon where order_number = '" . $orderNumber . "' and workorder_id = " . $v['id'] . " and order_type = 2 limit 1)")
                    ->find();
                if (!empty($memberVoucherInfo)) {
                    $settlement_service_info = $memberVoucherInfo['settlement_price'];
                    if (!empty($settlement_service_info)) {
                        $settlement_service_info = json_decode($settlement_service_info, true);
                        $settlement_service_info = $settlement_service_info[$orderInfo['car_level']];
                        $info[$k]['settlement_type'] = 2;
                    }
                }
                if (empty($settlement_service_info)) {
                    # 系统服务
                    $settlement_service_info = Db::table('service_car_mediscount')->field('settlement_amount')
                        ->where(array('biz_id' => $orderInfo['biz_id'], 'service_id' => $v['server_id'], 'service_type' => 1, 'car_level_id' => $orderInfo['car_level']))
                        ->value('settlement_amount');
                    if (empty($settlement_service_info)) {
                        if ($v['biz_pid'] != 0) {
                            $settlement_service_info = $v['price'];
                        }
                    }
                }
            } else {
                # 自定义服务
                $settlement_service_info = $v['price'];
            }
            # 该服务使用卡券核销掉了,按门店服务设置的结算价格
            if ($v['coupon_mark'] == 2) {
                settleService:
                $should_settle = $settlement_service_info;
                # 抽成金额
                if ($v['custommark'] == 1) {
                    # 系统服务
                    $withdrawal_amount = $should_settle * $bizInfo['extract_platservice'];
                } else {
                    $withdrawal_amount = $should_settle * $bizInfo['extract_selfservice'];
                }
                # 实际结算价格
                $settlement_service = $should_settle - $withdrawal_amount;
                # 记录结算,计算提成时要使用的价格
                $info[$k]['price_settlement_real'] = $settlement_service_info;
            } else {
                if ($payType == 5) {
                    # 余额支付,
                    goto settleService;
                } elseif ($payType == 1 or $payType == 2) {
                    # 微信支付/支付宝支付
                    if ($bizInfo['settlement_method'] == 2) {
                        # 按订单价格结算
                        $settlement_service_info = $v['original_price'];
                    }
                    $should_settle = $settlement_service_info;
                    # 抽成金额
                    if ($v['custommark'] == 1) {
                        $withdrawal_amount = $should_settle * $bizInfo['extract_platservice'];
                    } else {
                        # 自定义服务
                        $withdrawal_amount = $should_settle * $bizInfo['extract_selfservice'];
                    }
                    # 实际结算价格
                    $settlement_service = $should_settle - $withdrawal_amount;
                    # 记录结算,计算提成时要使用的价格  $v['original_price']
                    $info[$k]['price_settlement_real'] = $settlement_service_info;
                }
            }
            if ($v['custommark'] == 1) {
                # 系统服务,最终结算价格
                if ($v['relation_eva'] == 1) {
                    # 该服务 关联用户评价
                    if($v['score']==5){
                        $settlement_medium = config('ecarcoo.comment_rate_settlement')['good'];
                    }
                    if($v['score'] < 3){
                        $settlement_medium = config('ecarcoo.comment_rate_settlement')['bad'];
                    }
                    $final_settlement = $settlement_service * $settlement_medium;
                } else {
                    # 不关联
                    $final_settlement = $settlement_service;
                }
            } else {
                # 自定义服务
                $final_settlement = $settlement_service;
            }
            # 修改最终结算价格
            $info[$k]['final_settlement_real'] = $final_settlement;
            $epsilon = 0.01;
            $title = $bizInfo['biz_title'];
            if(abs(floatval($v['final_settlement'])-floatval($final_settlement)) < $epsilon){
                # 相等
                unset($info[$k]);
            }else{
                # 不相等
                $diff = floatval($v['final_settlement'])-floatval($final_settlement);
                $info[$k]['final_diff'] = $diff;
                if(array_key_exists($v['biz_id'],$bizArr)){
                    $bizArr[$v['biz_id']]['diff'] += $diff;
                }else{
                    $bizArr[$v['biz_id']]['diff'] = $diff;
                    $bizArr[$v['biz_id']]['biz_id'] = $v['biz_id'];
                    $bizArr[$v['biz_id']]['title'] = $title;
                }
                $info[$k]['desposit_status'] = Db::table('biz_settlement')->where(array('order_number'=>$v['order_number']))->value('desposit_status');
                $info[$k]['settlement_status'] = Db::table('biz_settlement')->where(array('order_number'=>$v['order_number']))->value('settlement_status');
                if(array_key_exists($title,$res)){
                    array_push($res[$title],$info[$k]);
                }else{
                    $res[$title][] = $info[$k];
                }
            }
        }
        dump($res);
        dump($bizArr);
        $et = [
            ['name' => '订单编号', 'field' => 'order_number'],
            ['name' => '车牌号', 'field' => 'car_num'],
            ['name' => '服务名称', 'field' => 'serviceTitle'],
            ['name' => '服务价格', 'field' => 'price'],
            ['name' => '服务时间', 'field' => 'order_starttime'],
            ['name' => '评分', 'field' => 'score'],
            ['name' => '当前应结算价格', 'field' => 'price_settlement'],
            ['name' => '当前最终结算价格', 'field' => 'final_settlement'],
            ['name' => '实际应结算价格', 'field' => 'price_settlement_real'],
            ['name' => '实际最终结算价格', 'field' => 'final_settlement_real'],
            ['name' => '差值', 'field' => 'final_diff']
        ];
        $excel_params = [
            'filename' => '铭赫汽车服务中心',
            'title' => $et,
            'data' => $res['铭赫汽车服务中心']
        ];
        $excel_params1 = [
            'filename' => 'E联车服红福店',
            'title' => $et,
            'data' => $res['E联车服红福店']
        ];
        $excel_params2 = [
            'filename' => '八方汽车美容中心',
            'title' => $et,
            'data' => $res['八方汽车美容中心']
        ];
        $excel_params3 = [
            'filename' => '万达七号车馆',
            'title' => $et,
            'data' => $res['万达七号车馆']
        ];
//        $excel = new Excel($excel_params);
//        $excel1 = new Excel($excel_params1);
//        $excel2 = new Excel($excel_params2);
        $excel3 = new Excel($excel_params3);
//        $excel->Export();
//        $excel1->Export();
//        $excel2->Export();
        $excel3->Export();
    }
}
